/**
 *
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛
 * 　　　　┃　　　┃神兽保佑
 * 　　　　┃　　　┃代码无BUG！
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━神兽出没━━━━━━coder-zhouxiongwei
 */
/**
 * Created by zhouxiongwei on 2019.03.25
 */

var DBFactory = require('../db/mysql_db');
var DBFactory_acc = require('../db/mysql_account_db');
var ScalpingDao = module.exports;
var PostHelper = require('../util/postHelper');
var crypto = require('crypto');

//查看自己获得利润
ScalpingDao.get_user_profit = function (data, cb) {
    var sql = 'select transfer_info.order_code, pay_goods.balance as total_balance, pay_goods.bussiness_profit, transfer_info.payee_account, transfer_info.balance as balance, ' +
        'transfer_info.payee_show_name, DATE_FORMAT(update_date, "%Y-%m-%d %H:%i:%s") as update_date, transfer_info.comment, transfer_info.real_name, transfer_info.user_type' +
        ' from transfer_info, pay_goods where payee_account = ? and transfer_status = 13 and pay_goods.order_code = transfer_info.order_code'
    var value = [data.ali_account];

    if (data.user_type) {
        sql += ' and user_type = ?';
        value.push(data.user_type);
    }

    DBFactory_acc.executeSql(sql, value, 'MallDao.check_goods_exist', autoCbErrFunction(cb, function (result) {
        var info = result && result.length > 0 ? result : null;
        var profit = 0;
        console.log(result);

        if (!info) {
            cb(null, {
                status: 201,
                msg: '抱歉，未查找到已获得利润信息!'
            });
        } else {
            for (var i = 0; i < info.length; i++) {
                profit += info[i].balance;

                if (data.user_type == 1) {
                    info[i].total_balance = info[i].bussiness_profit;
                    delete info[i].bussiness_profit;
                    info[i].tkRate = info[i].balance / info[i].total_balance;
                    info[i].tkRate = info[i].tkRate.toFixed(2);
                } else if (data.user_type && data.user_type != 0) {
                    delete info[i].bussiness_profit;
                    info[i].tkRate = info[i].balance / info[i].total_balance;
                    info[i].tkRate = info[i].tkRate.toFixed(2);
                } else {
                    info[i].total_balance = info[i].total_balance + info[i].bussiness_profit;
                    delete info[i].bussiness_profit;
                    info[i].tkRate = info[i].balance / info[i].total_balance;
                    info[i].tkRate = info[i].tkRate.toFixed(2);
                }
            }

            if (data.detail == 1) {
                cb(null, {
                    status: 200,
                    msg: info
                });
            } else {
                cb(null, {
                    status: 200,
                    msg: {
                        payee_account: info[0].payee_account,
                        balance: profit.toFixed(2),
                        payee_show_name: info[0].payee_show_name,
                        real_name: info[0].real_name
                    }
                });
            }
        }
    }));
}

//查询用户购买订单
ScalpingDao.show_goods_order = function (data, cb) {
    var sql = 'select * from pay_goods where account = ? and pay_status = 13 and showcase_status = ?';
    var value = [data.user_id, data.showcase_status];

    DBFactory_acc.executeSql(sql, value, 'ScalpingDao.show_goods_order', autoCbErrFunction(cb, function (result) {
        var goodsInfo = result && result.length > 0 ? result : null;

        if (!goodsInfo) {
            cb(null, {status: 201, msg: '抱歉，未查找到购买商品订单!' });
        } else {
            cb(null, {status: 200,msg: goodsInfo});
        }
    }));
}

//查询业务员等级
ScalpingDao.get_user_scale = function (data, cb) {
    var sql = 'select rank from users where account = ?';
    var value = [data];

    DBFactory_acc.executeSql(sql, value, 'ScalpingDao.show_goods_order', autoCbErrFunction(cb, function (result) {
        var goodsInfo = result && result.length > 0 ? result[0] : null;


        if (!goodsInfo) {
            cb(null, {status: 201, msg: '抱歉，用户不存在或类型非业务员!' });
        } else {
            cb(null, {status: 200, msg: goodsInfo.rank});
        }
    }));
}

//商品库是否存在该商品
ScalpingDao.check_goods_exist = function (data, cb) {
    var sql = 'select totalNum, count(*) as goods_count from sync_goods where id = ?';
    var value = [data.id];
    var info = [];

    DBFactory.executeSql(sql, value, 'MallDao.check_goods_exist', autoCbErrFunction(cb, function (result) {
        if (result[0].goods_count == 0) {
            info.status = 200;
            cb(null, info);
        } else {
            info.status = 201;
            cb(null, {
                status: info.status,
                totalNum: result[0].totalNum,
                desc: '抱歉，该商品已存在'
            });
        }
    }));
}

//查询商品佣金值
ScalpingDao.get_tkRate = function (data, cb) {
    var sql = 'select title, score, tkRate, tkCommFee from sync_goods where id = ?';
    var value = [data.gid];

    DBFactory.executeSql(sql, value, 'MallDao.get_tkRate', autoCbErrFunction(cb, function (result) {
        var goodsInfo = result && result.length > 0 ? result[0] : null;
        console.log(goodsInfo);

        if (!goodsInfo) {
            cb(null, {
                status: 201,
                msg: '抱歉，未查找到商品信息!'
            });
        } else {
            if (!goodsInfo.tkRate || !goodsInfo.tkCommFee) {
                cb(null, {
                    status: 201,
                    msg: '抱歉，未查找到商品佣金信息!'
                });
            } else {
                cb(null, {
                    status: 200,
                    msg: goodsInfo
                });
            }
        }
    }));
}

//通过订单佣金状态状态查询订单数据
ScalpingDao.search_order_by_status = function (data, cb) {
    var sql = 'select * from pay_goods where pay_status = 13';
    var value = [];

    if (data.balance_status) {
        sql += ' and balance_status = ? and balance > 0 and app_sid = ?';
        value.push(data.balance_status);
        value.push(data.app_sid);

        if(data.goods_type){
            sql += ' and goods_type = ?';
            value.push(data.goods_type);
        }

        if(data.app_sid == 'FTK'){
            sql += ' and goods_type = 1';
        }
    }
    if (data.bussiness_status) {
        sql += ' and bussiness_status = ? and app_sid != "eeqqq" and bussiness_profit > 0';
        value.push(data.bussiness_status);
    }

    DBFactory_acc.executeSql(sql, value, 'MallDao.search_order_by_status', autoCbErrFunction(cb, function (result) {
        var goodsInfo = result && result.length > 0 ? result : null;

        if (!goodsInfo) {
            cb(null, {
                status: 201,
                msg: '抱歉，未查找到购买商品数据!'
            });
        } else {
            cb(null, {
                status: 200,
                msg: goodsInfo
            });
        }
    }));
}

//查询平台各级分润比例
ScalpingDao.get_classify_profit = function (data, cb) {
    var sql = 'select * from share_goods_profit where app_sid = ?';
    var value = [data.app_sid];

    DBFactory.executeSql(sql, value, 'MallDao.get_classify_profit', autoCbErrFunction(cb, function (result) {
        var goodsInfo = result && result.length > 0 ? result[0] : null;

        if (!goodsInfo) {
            cb(null, {
                status: 201,
                msg: '抱歉，平台未设置分润比例!'
            });
        } else {
            cb(null, {
                status: 200,
                msg: goodsInfo
            });
        }
    }));
}

//判断用户是否为业务员
ScalpingDao.check_user_type = function (data, cb) {
    var sql = 'select count(*) as user_count from users where account = ? and length(rank) > 0';
    var value = [data.user_id];

    DBFactory_acc.executeSql(sql, value, 'ScalpingDao.check_user_type', autoCbErrFunction(cb, function (result) {
        var usersInfo = result && result.length > 0 ? result[0] : null;

        if (usersInfo.user_count == 0) {
            cb(null, {
                status: 201,
                msg: '抱歉，普通用户购买商品无法分润!'
            });
        } else if (usersInfo.user_count == 1) {
            cb(null, {
                status: 200,
                msg: '恭喜，用户为业务员可以进行分润操作!'
            });
        }
    }));
}

//判断推荐人是否都已打款
ScalpingDao.check_recommend_remit = function (data, cb) {
    var sql = 'select count(*) as user_count from transfer_info where order_code = ? and payee_account in ? and user_type = ?';
    var value = [data.orderCode, [data.check_user_remit], data.user_type];

    DBFactory_acc.executeSql(sql, value, 'ScalpingDao.check_recommend_remit', autoCbErrFunction(cb, function (result) {
        var usersInfo = result && result.length > 0 ? result[0] : null;
        console.log(usersInfo);

        if (usersInfo.user_count != data.recommendUserCount) {
            cb(null, {
                status: 200,
                msg: '抱歉，用户还未全部打款!'
            });
        } else {
            cb(null, {
                status: 201,
                msg: '所有用户打款成功,不能再次打款!'
            });
        }
    }));
}

//更新用户状态码
ScalpingDao.update_balance_status = function (data, cb) {
    var sql = "update pay_goods set balance_status= 1 where order_code = ? and account = ?";
    var value = [data.orderCode, data.user_id];

    DBFactory_acc.executeSql(sql, value, 'ScalpingDao.check_recommend_remit', autoCbErrFunction(cb, function (result) {
        if (result.changedRows == 0) {
            cb(null, {
                status: 201,
                desc: '更新用户状态码失败!'
            });
            return;
        } else {
            cb(null, {
                status: 200,
                desc: '推荐人已全部打款,更新用户状态码成功!'
            });
        }
    }));
}

//更新商户状态码
ScalpingDao.update_bussiness_status = function (data, cb) {
    var sql = "update pay_goods set bussiness_status= 1 where order_code = ?";
    var value = [data.orderCode];

    DBFactory_acc.executeSql(sql, value, 'ScalpingDao.update_bussiness_status', autoCbErrFunction(cb, function (result) {
        if (result.changedRows == 0) {
            cb(null, {
                status: 201,
                desc: '更新商户状态码失败!'
            });
            return;
        } else {
            cb(null, {
                status: 200,
                desc: '更新商户状态码成功!'
            });
        }
    }));
}

//将额外利润还给商户
ScalpingDao.add_extra_profit = function (data, cb) {
    var sql = "update pay_goods set balance = balance - ?, bussiness_profit = bussiness_profit + ?, extra_status = 1 where id = ? and extra_status = 0";
    var value = [data.extra, data.extra, data.id];

    DBFactory_acc.executeSql(sql, value, 'ScoreMallDao.add_extra_profit', autoCbErrFunction(cb, function (result) {
        if (result.changedRows == 0) {
            cb(null, {
                status: 201,
                desc: '更新额外利润失败!'
            });
            return;
        } else {
            cb(null, {
                status: 200,
                desc: '更新额外利润成功!'
            });
        }
    }));
}

//用户进行支付宝认证
ScalpingDao.bind_aliAccount = function (data, cb) {
    var sql = "update users set ali_account = ?, real_name = ? where account = ?";
    var value = [data.ali_account, data.real_name, data.user_id];

    DBFactory_acc.executeSql(sql, value, 'ScoreMallDao.bind_aliAccount', autoCbErrFunction(cb, function (result) {
        if (result.changedRows == 0) {
            cb(null, {
                status: 201,
                desc: '抱歉，你未做任何修改!'
            });
            return;
        } else {
            cb(null, {
                status: 200,
                desc: '支付宝认证成功!'
            });
        }
    }));
}

//存取订单前先取到商品佣金值以及商户可得利润
ScalpingDao.get_commission_profit = function (data, cb) {
    var sql = 'select score, tkRate, tkCommFee from sync_goods where id = ?';
    var value = [data.gid];

    DBFactory.executeSql(sql, value, 'MallDao.get_commission_profit', autoCbErrFunction(cb, function (result) {
        var goodsInfo = result && result.length > 0 ? result[0] : null;
        if (!goodsInfo) {
            cb(null, {
                status: 201,
                msg: '抱歉，未查找到商品数据!'
            });
        } else {
            if (goodsInfo.tkRate == null || goodsInfo.tkRate == "") {
                goodsInfo.tkRate = 0.1;
                goodsInfo.tkCommFee = parseInt(goodsInfo.score * 0.3) * goodsInfo.tkRate;
            }
            cb(null, {
                status: 200,
                bussiness_profit: data.num - goodsInfo.tkCommFee,
                balance: goodsInfo.tkCommFee
            });
        }
    }));
}

//查找橱窗商户登录账号
ScalpingDao.get_merchant_account = function (data, cb) {
    var sql = 'select id, account from sync_goods where id = ?';
    var value = [data.gid];

    DBFactory.executeSql(sql, value, 'MallDao.get_merchant_account', autoCbErrFunction(cb, function (result) {
        var goodsInfo = result && result.length > 0 ? result[0] : null;

        if (!goodsInfo) {
            cb(null, {
                status: 201,
                msg: '抱歉，未查找到用户账号数据!'
            });
        } else {
            if(goodsInfo.account == null || goodsInfo.account.length < 6){
                cb(null, {
                    status: 201,
                    msg: '该订单为金豆商城商品，无商户利润。'
                });
            }else{
                cb(null, {
                    status: 200,
                    userInfo: goodsInfo
                });
            }
        }
    }));
}

//判断打款订单订单状态
ScalpingDao.check_remit_exist = function (data, cb) {
    var sql = 'select transfer_status from transfer_info where order_code = ? and payee_account = ? and user_type = ?';
    var value = [data.orderCode, data.ali_account, data.user_type];

    DBFactory_acc.executeSql(sql, value, 'ScalpingDao.check_remit_exist', autoCbErrFunction(cb, function (result) {
        var goodsInfo = result && result.length > 0 ? result[0] : null;

        if (!goodsInfo) {
            cb(null, {
                status: 200,
                msg: '抱歉，未查找到打款订单数据!'
            }); //订单不存在，接入打款系统，给用户进行打款
        } else {
            if (goodsInfo.transfer_status == 12) {
                cb(null, {
                    status: 201,
                    msg: '该订单未打款!'
                });
            } else if (goodsInfo.transfer_status == 13) {
                cb(null, {
                    status: 201,
                    msg: '该订单已打款，不能重复操作!'
                });
            } else if (goodsInfo.transfer_status == 14) {
                cb(null, {
                    status: 201,
                    msg: '该订单打款失败，请查看失败原因!!'
                });
            }
        }
    }));
}

//查找小伙伴成员
ScalpingDao.get_friend_list = function (data, cb) {
    var sql = 'select users.uid, ua.app_sid, DATE_FORMAT(created_time, "%Y-%m-%d %H:%i:%s") as created_date, ua.account, ua.money from users, user_app_new_agent ua where users.account = ua.recommender and users.account = ?';
    var value = [data.user_id];

    DBFactory_acc.executeSql(sql, value, 'MallDao.get_friend_list', autoCbErrFunction(cb, function (result) {
        var usersInfo = result && result.length > 0 ? result : null;

        if (!usersInfo) {
            cb(null, {
                status: 201,
                msg: '抱歉，你尚未有小伙伴加入!'
            });
        } else {
            var recommendCode = uidToCode(usersInfo[0].uid);
            for (var i = 0; i < usersInfo.length; i++) {
                delete usersInfo[i].uid;
            }
            cb(null, {
                status: 200,
                recommendCode: recommendCode,
                usersInfo: usersInfo,

            });
        }
    }));
}

//查找用户的支付宝账号
ScalpingDao.get_user_aliaccount = function (data, cb) {
    var sql = 'select uid, account, ali_account, real_name from users where account = ?';
    var value = [data.user_id];

    DBFactory_acc.executeSql(sql, value, 'MallDao.get_user_aliaccount', autoCbErrFunction(cb, function (result) {
        var goodsInfo = result && result.length > 0 ? result[0] : null;

        if (!goodsInfo) {
            cb(null, {
                status: 201,
                msg: '抱歉，未查找到用户信息数据!'
            });
        } else {
            if (!goodsInfo.ali_account || !goodsInfo.real_name) {
                cb(null, {
                    status: 201,
                    msg: '抱歉，请先支付宝认证!'
                });
            } else {
                cb(null, {
                    status: 200,
                    userInfo: goodsInfo
                });
            }
        }
    }));
}

//判断库存量是否改变
ScalpingDao.changed_totalNum = function (data, cb) {
    var sql = "update sync_goods set totalNum = ? where id = ?";
    var value = [data.totalNum, data.id];

    DBFactory.executeSql(sql, value, 'ScoreMallDao.changed_totalNum', autoCbErrFunction(cb, function (result) {
        if (result.changedRows == 0) {
            cb(null, {
                status: 201,
                desc: '更新库存量失败!'
            });
            return;
        } else {
            cb(null, {
                status: 200,
                desc: '更新库存量成功!'
            });
        }
    }));
}

//更新打款信息表
ScalpingDao.uodateTransferInfo = function (data, cb) {
    var sql = "update transfer_info set transfer_status = ?, update_date = ?, comment = ?, pay_order = ? where order_code = ? and payee_account = ?";
    var value = [data.transfer_status, data.update_date, data.comment, data.pay_order, data.order_code, data.payee_account];

    DBFactory_acc.executeSql(sql, value, 'ScoreMallDao.uodateTransferInfo', autoCbErrFunction(cb, function (result) {
        if (result.changedRows == 0) {
            cb(null, {
                status: 201,
                desc: '更新打款信息失败!'
            });
            return;
        } else {
            if(data.transfer_status == 13){
                cb(null, {
                    status: 200,
                    desc: '打款成功!'
                });
            }else{
                cb(null, {
                    status: 201,
                    desc: '打款失败!'
                });
            }
            
        }
    }));
}

ScalpingDao.saveGoods = function (data, cb) {
    var sql = "insert into sync_goods set ?";

    DBFactory.executeSql(sql, data, 'ScoreMallDao.saveGoods', autoCbErrFunction(cb, function (result) {
        // console.log(result);

        if (!result.insertId) {
            cb(null, {
                desc: '保存商品数据失败',
                status: 201
            });
            return;
        } else {
            cb(null, {
                desc: '保存商品数据成功!',
                status: 200
            });
        }
    }));
}

//打款前保存打款信息，状态为未打款
ScalpingDao.saveTransferInfo = function (data, cb) {
    var sql = "insert into transfer_info set ?";

    var info = {
        order_code: data.orderCode,
        payee_type: data.payee_type,
        payee_account: data.user_id,
        balance: data.balance,
        payee_show_name: data.payer_show_name,
        remark: '支付宝打款',
        transfer_status: 12,
        created_date: new Date(),
        real_name: data.payee_real_name,
        user_type: data.user_type
    };

    DBFactory_acc.executeSql(sql, info, 'ScoreMallDao.saveTransferInfo', autoCbErrFunction(cb, function (result) {

        if (result.affectedRows != 1) {
            cb(null, {
                desc: '保存打款信息失败',
                status: 201
            });
            return;
        } else {
            cb(null, {
                desc: '保存打款信息成功!',
                status: 200
            });
        }
    }));
}

ScalpingDao.get_access_token = function (data, cb) { //调用接口查询用户积分
    data.platInfo = 'https://github.com/login/oauth/access_token';

    var param = {
        platInfo: data.platInfo,
        link_param: {
            client_id: data.client_id,
            client_secret: data.client_secret,
            code: data.code
        }
    };

    PostHelper.baseRequestByWL(param.platInfo, param.link_param, function (err, data) {
        if (err) {
            console.log(err);
            console.log('访问平台' + link_param.key + '发送失败，通知数据:');
            cb('访问出错，请联系客服 Err:request plat failed ');
            return;
        }

        cb(null, data);
    });
}

ScalpingDao.get_access_token_wb = function (data, cb) { //调用接口查询用户积分
    data.platInfo = 'https://api.weibo.com/oauth2/access_token';

    var param = {
        platInfo: data.platInfo,
        link_param: {
            client_id: '978495094',
            client_secret: 'b3c7cdd2911d87b50628d57679a062f4',
            code: data.code,
            grant_type: 'authorization_code',
            redirect_uri: 'http://www.niyueling.cn:6006'
        }
    };

    PostHelper.baseRequest(param.platInfo, param.link_param, function (err, data) {
        if (err) {
            console.log(err);
            console.log('访问平台' + link_param.key + '发送失败，通知数据:');
            cb('访问出错，请联系客服 Err:request plat failed ');
            return;
        }

        cb(null, data);
    });
}

ScalpingDao.get_user_token = function (data, cb) { //调用接口查询用户积分
    data.platInfo = 'https://api.github.com/user';

    var param = {
        platInfo: data.platInfo,
        link_param: {
            access_token: data.access_token
        }
    };

    PostHelper.baseRequest1(param.platInfo, param.link_param, function (err, data) {
        if (err) {
            console.log(err);
            console.log('访问平台发送失败，通知数据:');
            cb('访问出错，请联系客服 Err:request plat failed ');
            return;
        }

        cb(null, data);
    });
}

ScalpingDao.get_token_info = function (data, cb) { //调用接口查询用户积分
    data.platInfo = 'https://api.weibo.com/oauth2/get_token_info';

    var param = {
        platInfo: data.platInfo,
        link_param: {
            access_token: data.access_token
        }
    };

    PostHelper.baseRequest(param.platInfo, param.link_param, function (err, data) {
        if (err) {
            console.log(err);
            console.log('访问平台发送失败，通知数据:');
            cb('访问出错，请联系客服 Err:request plat failed ');
            return;
        }

        cb(null, data);
    });
}

ScalpingDao.get_user_info = function (data, cb) { //调用接口查询用户积分
    data.platInfo = 'https://api.weibo.com/2/users/show.json';

    var param = {
        platInfo: data.platInfo,
        link_param: {
            access_token: data.access_token,
            uid: data.uid
        }
    };

    PostHelper.baseRequest1(param.platInfo, param.link_param, function (err, data) {
        if (err) {
            console.log(err);
            console.log('访问平台发送失败，通知数据:');
            cb('访问出错，请联系客服 Err:request plat failed ');
            return;
        }

        cb(null, data);
    });
}

ScalpingDao.check_wbid_exist = function (data, cb) {
    var sql = 'select count(*) as count from wbusers where wbid = ?';
    var value = [data.wbid];

    DBFactory_acc.executeSql(sql, value, 'ScalpingDao.check_wbid_exist', autoCbErrFunction(cb, function (result) {
        var usersInfo = result && result.length > 0 ? result[0] : null;

        if (usersInfo.count == 0) {
            cb(null, {
                status: 200,
                msg: '恭喜，用户尚未注册!'
            });
        } else {
            cb(null, {
                status: 201,
                msg: '抱歉，用户已经绑定微博!'
            });
        }
    }));
}

ScalpingDao.saveWbUsers = function (data, cb) {
    var sql = "insert into wbusers set ?";

    DBFactory_acc.executeSql(sql, data, 'ScalpingDao.saveWbUsers', autoCbErrFunction(cb, function (result) {

        if (result.affectedRows != 1) {
            cb(null, {
                desc: '保存用户信息失败',
                status: 201
            });
            return;
        } else {
            cb(null, {
                desc: '保存用户信息成功!',
                status: 200
            });
        }
    }));
}

ScalpingDao.check_shopping_cart_exist = function (data, cb) {
    var sql = 'select count(*) as count from shopping_cart where gid = ? and user_id = ?';
    var value = [data.gid, data.user_id];

    DBFactory_acc.executeSql(sql, value, 'ScalpingDao.check_shopping_cart_exist', autoCbErrFunction(cb, function (result) {
        var usersInfo = result && result.length > 0 ? result[0] : null;

        if (usersInfo.count == 0) {
            cb(null, {
                status: 200,
                msg: '恭喜，该商品可加入购物车!'
            });
        } else {
            cb(null, {
                status: 201,
                msg: '抱歉，该商品已加入购物车!'
            });
        }
    }));
}

ScalpingDao.save_shopping_cart = function (data, cb) { 
    var sql = "insert into shopping_cart set ?";

    var shopping_cart = {
        gid: parseInt(data.gid),
        title: data.title,
        good_title: data.good_title,
        zk_price: data.zk_price,
        score: data.score,
        created_date: new Date(),
        user_id: data.user_id,
        shop_img: data.shop_img
    }

    DBFactory_acc.executeSql(sql, shopping_cart, 'ScalpingDao.save_shopping_cart', autoCbErrFunction(cb, function (result) {

        if (result.affectedRows != 1) {
            cb(null, {
                desc: '保存购物车失败',
                status: 201
            });
            return;
        } else {
            cb(null, {
                desc: '保存购物车成功!',
                status: 200
            });
        }
    }));
}

ScalpingDao.forword_transfer_commission = function (data, cb) { //调用接口查询用户积分
    data.platInfo = 'http://api.weetaoke.com/payment/transfer_commission';

    var param = {
        platInfo: data.platInfo,
        link_param: {
            orderCode: data.orderCode,
            user_id: data.user_id,
            balance: data.balance,
            payer_show_name: data.payer_show_name,
            payee_real_name: data.payee_real_name,
            user_type: data.user_type
        }
    };

    PostHelper.baseRequestByWL(param.platInfo, param.link_param, function (err, data) {
        if (err) {
            console.log(err);
            console.log('访问平台' + link_param.key + '发送失败，通知数据:');
            cb('访问出错，请联系客服 Err:request plat failed ');
            return;
        }

        cb(null, data);
    });
}

//同步金豆商城商品
ScalpingDao.syncGoods = function (data, cb) { //调用接口查询用户积分
    data.platInfo = 'https://www.kuailezhizao.com/open/sync_goods/syncGoods';
    data.key = 'BM2019320095638666';
    data.secret = 'P2wbe2r3iyCJxweX';

    var param = {
        platInfo: data.platInfo,
        link_param: {
            synckey: data.synckey,
            key: data.key,
            time: new Date().getTime().toString(),
            secret: data.secret,
            size: data.size,
            columns: data.columns
        }
    };

    if (!param.link_param.size) {
        delete param.link_param.size;
    }

    if (!param.link_param.columns) {
        delete param.link_param.columns;
    }

    requestBase(param, autoCbErrFunction(cb, function (result) {
        console.log(result);
        var value = result.payload.new_data;
        var synckey = result.payload.synckey;

        if (data.synckey == result.payload.synckey) {
            data.status = 202;
            cb(null, {
                status: 202,
                msg: '金豆商城数据更新成功!'
            });
        } else {
            data.status = 200;
            cb(null, {
                synckey: synckey,
                data: value
            });
        }
    }));
}

//调用我方同步金豆商城接口，进行实时更新金豆商城数据
//同步金豆商城商品
ScalpingDao.update_key = function (data, cb) { //调用接口查询用户积分
    data.platInfo = 'http://127.0.0.1:9000/scalping/sync_goods_test';

    var param = {
        platInfo: data.platInfo,
        link_param: {
            synckey: data.updatekey
        }
    };

    if (!data.updatekey) {
        param.link_param.synckey = 0;
    }

    console.log(param);

    requestBySelf(param, autoCbErrFunction(cb, function (result) {
        var value = result.payload.new_data;
        var synckey = result.payload.synckey;
        console.log(result.payload.synckey);

        if (data.updatekey == result.payload.synckey) {
            data.status = 201;
            cb(null, {
                synckey: synckey
            });
        } else {
            data.status = 200;
            cb(null, {
                synckey: synckey,
                data: value
            });
        }
    }));
}

//金豆商城商品列表
ScalpingDao.get_zd_goods = function (data, cb) { //调用接口查询用户积分
    data.platInfo = 'https://www.kuailezhizao.com/open/goods/get_zd_goods';
    data.key = 'BM2019320095638666';
    data.secret = 'P2wbe2r3iyCJxweX';

    var param = {
        platInfo: data.platInfo,
        link_param: {
            key: data.key,
            time: new Date().getTime().toString(),
            secret: data.secret,
            page: data.page,
            size: data.size
        }
    };

    if (!param.link_param.size) {
        delete param.link_param.size;
    }

    if (!param.link_param.page) {
        delete param.link_param.page;
    }

    requestBase(param, autoCbErrFunction(cb, function (result) {
        cb(null, result);
    }));
}

//保存收货地址
ScalpingDao.save_addr = function (data, cb) { //调用接口查询用户积分
    data.platInfo = 'https://www.kuailezhizao.com/open/address/save';
    data.key = 'BM2019320095638666';
    data.secret = 'P2wbe2r3iyCJxweX';

    var param = {
        platInfo: data.platInfo,
        link_param: {
            key: data.key,
            secret: data.secret,
            time: new Date().getTime().toString(),
            province: data.province,
            city: data.city,
            street: data.street,
            detail: data.detail,
            post_code: data.post_code,
            name: data.name,
            tel: data.tel,
            Is_default: data.Is_default
        }
    };

    if (!param.link_param.Is_default) {
        delete param.link_param.Is_default;
    }

    requestBase(param, autoCbErrFunction(cb, function (result) {
        cb(null, result);
    }));
}

ScalpingDao.save_addr_plat = function (data, cb) {
    var sql = "insert into reing_addr set ?";
    value = {
        addr_id: parseInt(data.addr_id),
        real_name: data.name,
        account: data.tel,
        post_code: data.post_code,
        province: data.province,
        city: data.city,
        street: data.street,
        detail: data.detail,
        created_date: new Date(),
        login_account: data.login_account,
        is_default: data.is_default
    };

    DBFactory.executeSql(sql, value, 'ScoreMallDao.save_addr_plat', autoCbErrFunction(cb, function (result) {

        if (!result.insertId) {
            data.status = 201;
            cb(null, {
                desc: '保存用户地址失败',
                code: 400
            });
            return;
        } else {
            data.status = 200;
            cb(null, {
                desc: '保存用户地址成功!',
                code: 200
            });
        }
    }));
}

ScalpingDao.update_default_addr = function (data, cb) {

    var sql = "update reing_addr set is_default = 0 where account = ? and real_name = ?";
    var value = [data.tel, data.name];

    DBFactory.executeSql(sql, value, 'ScoreMallDao.update_default_addr', autoCbErrFunction(cb, function (result) {
        console.log(result);
        if (result.changedRows == 0) {
            data.status = 201;
            cb(null, {
                status: 201,
                desc: '更新默认地址表示失败!'
            });
            return;
        } else {
            data.status = 200;
            cb(null, {});
        }
    }));
}

//查看地址列表
ScalpingDao.addr_list = function (data, cb) { //调用接口查询用户积分
    data.platInfo = 'https://www.kuailezhizao.com/open/address/list';
    data.key = 'BM2019320095638666';
    data.secret = 'P2wbe2r3iyCJxweX';

    var param = {
        platInfo: data.platInfo,
        link_param: {
            key: data.key,
            secret: data.secret,
            time: new Date().getTime().toString(),
            size: data.size,
            page: data.page,
            shop_id: data.shop_id
        }
    };

    if (!param.link_param.size) {
        delete param.link_param.size;
    }
    if (!param.link_param.page) {
        delete param.link_param.page;
    }
    if (!param.link_param.shop_id) {
        delete param.link_param.shop_id;
    }

    requestBase(param, autoCbErrFunction(cb, function (result) {
        cb(null, result);
    }));
}

//返回一个地址(有默认地址则返回默认地址)
ScalpingDao.get_addr = function (data, cb) { //调用接口查询用户积分
    data.platInfo = 'https://www.kuailezhizao.com/open/address/getAddr';
    data.key = 'BM2019320095638666';
    data.secret = 'P2wbe2r3iyCJxweX';

    var param = {
        platInfo: data.platInfo,
        link_param: {
            key: data.key,
            secret: data.secret,
            time: new Date().getTime().toString(),
            shop_id: data.shop_id
        }
    };

    if (!param.link_param.shop_id) {
        delete param.link_param.shop_id;
    }

    requestBase(param, autoCbErrFunction(cb, function (result) {
        cb(null, result);
    }));
}

//查询默认地址
ScalpingDao.get_addr_default = function (data, cb) {
    var sql = 'select * from reing_addr where login_account = ? order by created_date desc limit 10';
    var value = [data.account];

    DBFactory.executeSql(sql, value, 'MallDao.get_addr_default', autoCbErrFunction(cb, function (result) {
        var goodsInfo = result && result.length > 0 ? result : null;

        if (!goodsInfo) {
            data.status = 201;
            cb(null, '抱歉，未查找到地址信息!');
        } else {
            data.status = 200;
            cb(null, goodsInfo);
        }
    }));
}

//查询购物车记录
ScalpingDao.get_shopping_cart = function (data, cb) {
    var sql = 'select id, user_id, gid, title, good_title, zk_price, score, DATE_FORMAT(created_date, "%Y-%m-%d %H:%i:%s") as created_date from shopping_cart where user_id = ?';
    var value = [data.user_id];

    DBFactory_acc.executeSql(sql, value, 'MallDao.get_shopping_cart', autoCbErrFunction(cb, function (result) {
        var shopping_cart = result && result.length > 0 ? result : null;

        if (!shopping_cart) {
            cb(null, {status: 201, msg: '抱歉，未查找到购物车商品信息!'});
        } else {
            cb(null, {status: 200, msg: shopping_cart});
        }
    }));
}

//删除地址
ScalpingDao.del_addr = function (data, cb) { //调用接口查询用户积分
    data.platInfo = 'https://www.kuailezhizao.com/open/address/delete';
    data.key = 'BM2019320095638666';
    data.secret = 'P2wbe2r3iyCJxweX';

    var param = {
        platInfo: data.platInfo,
        link_param: {
            key: data.key,
            secret: data.secret,
            time: new Date().getTime().toString(),
            id: data.id
        }
    };

    requestBase(param, autoCbErrFunction(cb, function (result) {
        cb(null, result);
    }));
}

ScalpingDao.delete_shopping_cart = function (data, cb) {
    var sql = "delete from shopping_cart where user_id = ? and gid = ?";
    var value = [data.user_id, parseInt(data.gid)];

    DBFactory_acc.executeSql(sql, value, 'ScoreMallDao.delete_shopping_cart', autoCbErrFunction(cb, function (result) {
        if (result.affectedRows == 0) {
            cb(null, {
                status: 201,
                desc: '删除购物车商品失败!'
            });
            return;
        } else {
            cb(null, {
                status: 200,
                desc: '恭喜，删除购物车商品成功!'
            });
        }
    }));
}

ScalpingDao.del_addr_plat = function (data, cb) {
    var sql = "delete from reing_addr where addr_id = ?";
    var value = [parseInt(data.id)];

    DBFactory.executeSql(sql, value, 'ScoreMallDao.del_addr_plat', autoCbErrFunction(cb, function (result) {
        console.log(result);
        if (result.affectedRows == 0) {
            data.status = 201;
            cb(null, {
                status: 201,
                desc: '删除收货地址失败!'
            });
            return;
        } else {
            data.status = 200;
            cb(null, {
                status: 200,
                desc: '恭喜，删除收货地址成功!'
            });
        }
    }));
}

//创建订单
ScalpingDao.create_plat_order = function (data, cb) { //调用接口查询用户积分
    data.platInfo = 'https://www.kuailezhizao.com/open/order/createPlatOrder';
    data.key = 'BM2019320095638666';
    data.secret = 'P2wbe2r3iyCJxweX';

    data.goodsInfo = [{
        "gid": parseInt(data.gid),
        "num": parseInt(data.score),
        "comment": data.good_title
    }];
    data.goodsInfo = JSON.stringify(data.goodsInfo);
    console.log(data.goodsInfo);

    var param = {
        platInfo: data.platInfo,
        link_param: {
            key: data.key,
            secret: data.secret,
            time: new Date().getTime().toString(),
            addr_id: data.addr_id,
            goodsInfo: data.goodsInfo
        }
    };

    // console.log(param);

    requestBase(param, autoCbErrFunction(cb, function (result) {
        console.log(result);
        cb(null, result);
    }));
}

function requestBase(data, cb) {
    var needParam = ['platInfo', 'link_param'];
    if (checkHasParamAndCb(data, needParam, cb).err) return;

    var link_param = data.link_param;
    var link_url = data.platInfo;
    var secret = data.link_param.secret;
    delete link_param.secret;

    if (!link_url) {
        cb('操作异常 Err:Info setting error ');
        return;
    }

    // console.log(link_param);

    var requestParam = getSortObjByAsciiWithObj1(link_param, secret); //生成带加密sign的请求参数

    console.log(requestParam);

    PostHelper.baseRequestByWL(link_url, requestParam, function (err, data) {
        if (err) {
            console.log(err);
            console.log('访问平台' + link_param.key + '发送失败，通知数据:');
            cb('访问出错，请联系客服 Err:request plat failed ');
            return;
        }

        cb(null, data);
    });
}

function requestBySelf(data, cb) {
    var needParam = ['platInfo', 'link_param'];
    if (checkHasParamAndCb(data, needParam, cb).err) return;

    var link_param = data.link_param;
    var link_url = data.platInfo;

    if (!link_url) {
        cb('操作异常 Err:Info setting error ');
        return;
    }

    console.log(link_param);

    PostHelper.baseRequest(link_url, link_param, function (err, data) {
        if (err) {
            console.log(err);
            console.log('访问平台' + link_param.key + '发送失败，通知数据:');
            cb('访问出错，请联系客服 Err:request plat failed ');
            return;
        }

        cb(null, data);
    });
}

//id查询详细信息
ScalpingDao.id_to_goodsinfo = function (data, cb) {
    var sql = 'select * from sync_goods where id = ? and is_publish = 1';
    var value = [data.id];

    DBFactory.executeSql(sql, value, 'MallDao.id_to_goodsinfo', autoCbErrFunction(cb, function (result) {
        var goodsInfo = result && result.length > 0 ? result[0] : null;

        if (!goodsInfo) {
            data.status = 201;
            cb(null, '抱歉，未查找到该商品数据!');
        } else {
            data.status = 200;
            cb(null, goodsInfo);
        }
    }));
}

//判断商品是否存在规格
ScalpingDao.check_sku_length = function (data, cb) {
    var sql = 'select sku from sync_goods where id = ?';
    var value = [data.id];

    DBFactory.executeSql(sql, value, 'MallDao.check_sku_length', autoCbErrFunction(cb, function (result) {
        var goodsInfo = result && result.length > 0 ? result[0] : null;

        if (!goodsInfo) {
            data.status = 201;
            return cb(null, '抱歉，id未查找到对应数据!');
        } else {
            data.status = 200;
            return cb(null, goodsInfo);
        }
    }));
}

//查询sku指定规格剩下的库存量
ScalpingDao.specificate_to_id = function (data, cb) {
    var sql = 'select tag, id, pictUrl, totalNum, score, showcase_status from sync_goods';
    var value = [];

    if (data.id && data.sku_value == '{}') {
        sql += ' where id = ? and id = belong_id';
        value.push(data.id);
    } else {
        sql += ' where sku_value = ? and id != belong_id and belong_id = ?'
        value.push(data.sku_value, data.id);
    }

    DBFactory.executeSql(sql, value, 'MallDao.sku_total_count', autoCbErrFunction(cb, function (result) {
        var goodsInfo = result && result.length > 0 ? result[0] : null;

        if (!goodsInfo) {
            return cb(null, {
                status: 201,
                msg: '抱歉，未查找到该商品数据!'
            });
        } else {
            if (goodsInfo.totalNum > 0) {
                return cb(null, {
                    id: goodsInfo.id,
                    tag: goodsInfo.tag,
                    pics: goodsInfo.pictUrl,
                    totalNum: goodsInfo.totalNum,
                    desc: '该规格库存量',
                    score: goodsInfo.score,
                    showcase_status: goodsInfo.showcase_status,
                    status: 200
                });
            } else {
                return cb(null, {
                    status: 201,
                    msg: '抱歉，库存量不足!'
                });
            }
        }
    }));
}

//查询sku指定规格剩下的库存量
ScalpingDao.sku_total_count = function (data, cb) {
    var sql = 'select tag, id, pictUrl, totalNum from sync_goods where sku_value = ? and id != belong_id';
    var sku_value = {
        颜色分类: data.color,
        尺码: data.size
    }

    if (!data.size) {
        delete sku_value.尺码;
    }
    if (!data.color) {
        delete sku_value.颜色分类;
    }

    if (!data.size && !data.color) {
        sql = 'select tag, id, pictUrl, totalNum from sync_goods where id = ?'
        sku_value = [parseInt(data.id)];
    } else {
        sku_value = JSON.stringify(sku_value);
    }

    DBFactory.executeSql(sql, sku_value, 'MallDao.sku_total_count', autoCbErrFunction(cb, function (result) {
        var goodsInfo = result && result.length > 0 ? result[0] : null;

        if (!goodsInfo) {
            data.status = 201;
            return cb(null, '抱歉，未查找到该商品数据!');
        } else {
            if (goodsInfo.totalNum > 0) {
                data.status = 200;
                return cb(null, {
                    id: goodsInfo.id,
                    tag: goodsInfo.tag,
                    pics: goodsInfo.pictUrl,
                    totalNum: goodsInfo.totalNum,
                    desc: '该规格库存量'
                });
            } else {
                data.status = 201;
                return cb(null, '抱歉，库存量不足!');
            }
        }
    }));
}

//查询sku指定规格剩下的库存量
ScalpingDao.sku_total_count_opposite = function (data, cb) {
    var sql = 'select tag, id, pictUrl, totalNum from sync_goods where sku_value = ? and id != belong_id';
    var sku_value = {
        尺码: data.size,
        颜色分类: data.color
    }

    if (!data.size) {
        delete sku_value.尺码;
    }
    if (!data.color) {
        delete sku_value.颜色分类;
    }

    if (!data.size && !data.color) {
        sql = 'select tag, id, pictUrl, totalNum from sync_goods where id = ?'
        sku_value = [parseInt(data.id)];
    } else {
        sku_value = JSON.stringify(sku_value);
        console.log(sku_value);
    }

    DBFactory.executeSql(sql, sku_value, 'MallDao.sku_total_count', autoCbErrFunction(cb, function (result) {
        var goodsInfo = result && result.length > 0 ? result[0] : null;

        if (!goodsInfo) {
            data.status = 201;
            return cb(null, '抱歉，未查找到该商品数据!');
        } else {
            if (goodsInfo.totalNum > 0) {
                data.status = 200;
                return cb(null, {
                    id: goodsInfo.id,
                    tag: goodsInfo.tag,
                    pics: goodsInfo.pictUrl,
                    totalNum: goodsInfo.totalNum,
                    desc: '该规格库存量'
                });
            } else {
                data.status = 201;
                return cb(null, '抱歉，库存量不足!');
            }

        }
    }));
}

ScalpingDao.goods_classify = function (data, cb) {
    var sql = 'select * from sync_goods';
    var value = [];

    if (!data.type) {
        sql += ' group by title';
    } else {
        sql += ' where tag = ? group by title';
        value.push(data.type);
    }

    if (data.page && data.size) {
        sql += ' order by id limit ?, ?';
        var page = (parseInt(data.page) - 1) * data.size;
        var size = (parseInt(data.size));
        value.push(parseInt(page));
        value.push(parseInt(size));
    }

    DBFactory.executeSql(sql, value, 'MallDao.goods_classify', autoCbErrFunction(cb, function (result) {
        var goodsInfo = result && result.length > 0 ? result : null;

        if (!goodsInfo) {
            data.status = 201;
            cb(null, '已经加载到全部了!');
        } else {
            data.status = 200;
            cb(null, goodsInfo);
        }
    }));
}

ScalpingDao.get_goods_count_classify = function (data, cb) {
    var sql = 'select count(*) as goods_count from sync_goods';
    var value = [];

    if (data.type) {
        sql += ' where tag = ?';
        value.push(data.type);
    }

    DBFactory.executeSql(sql, value, 'MallDao.get_goods_count_classify', autoCbErrFunction(cb, function (result) {
        var goodsInfo = result && result.length > 0 ? result[0] : null;

        if (goodsInfo.goods_count == 0) {
            console.log(goodsInfo.goods_count);
            data.status = 201;
            cb(null, '抱歉，当前分类无商品数据!');
        } else {
            data.status = 200;
            cb(null, goodsInfo);
        }
    }));
}

ScalpingDao.goods_classify_gid = function (data, cb) {
    var sql = 'select * from sync_goods where is_publish = 1 and (plat_type = ? or LENGTH(plat_type)=0)';
    var value = [data.app_sid];

    if (data.aid != '0') {
        sql += ' and tag = ?';
        value.push(data.aid);
    }

    if (data.page && data.size) {
        sql += ' group by belong_id order by id limit ?, ?';
        var page = (parseInt(data.page) - 1) * data.size;
        var size = (parseInt(data.size));
        value.push(parseInt(page));
        value.push(parseInt(size));
    }

    DBFactory.executeSql(sql, value, 'MallDao.goods_classify', autoCbErrFunction(cb, function (result) {
        var goodsInfo = result && result.length > 0 ? result : null;

        if (!goodsInfo) {
            data.status = 201;
            cb(null, '已经加载到全部了!');
        } else {
            data.status = 200;
            cb(null, goodsInfo);
        }
    }));
}

ScalpingDao.get_goods_count_classify_gid = function (data, cb) {
    var sql = 'select count(*) as goods_count from sync_goods where is_publish = 1 and (plat_type = ? or LENGTH(plat_type)=0)';
    var value = [data.app_sid];

    if (data.aid && data.aid != '0') {
        sql += ' and tag = ?';
        value.push(data.aid);
    }
    DBFactory.executeSql(sql, value, 'MallDao.get_goods_count_classify', autoCbErrFunction(cb, function (result) {
        var goodsInfo = result && result.length > 0 ? result[0] : null;

        if (goodsInfo.goods_count == 0) {
            data.status = 201;
            cb(null, '抱歉，当前分类无商品数据!');
        } else {
            data.status = 200;
            cb(null, goodsInfo);
        }
    }));
}

//返回拼接上sign的请求对象
function getSortObjByAsciiWithObj1(obj, secret) {

    var sortArrStr = getSortStrByAsciiWithObj(obj); //组成按字母顺序排序的字符串
    var waitSecretStr = sortArrStr + secret; //使用前后加secret的方式拼接待加密字符串   
    console.log(waitSecretStr);
    var md5 = crypto.createHash('md5');
    md5.update(waitSecretStr);
    var stringSign = md5.digest('hex');
    var sign = stringSign.toLocaleLowerCase();
    obj.sign = sign;
    return obj;
}

//构造按Ascii码顺序组成的字符串
function getSortStrByAsciiWithObj(obj) {
    var arr = [];
    for (var key in obj) {
        arr.push(key);
    }
    var sortArr = getsParaFromArr(arr); //返回按字母顺序排序的数组
    var sortArrStr = '';
    sortArr.forEach(function (key) {
        var item = {};
        item[key] = obj[key];
        sortArrStr += key + '=' + obj[key];
    });

    return sortArrStr;
}

//传入数组，返回按Ascii码排序的数组
function getsParaFromArr(sParaTemp) {
    var sPara = [];
    //除去数组中的空值和签名参数
    for (var i1 = 0; i1 < sParaTemp.length; i1++) {
        var value = sParaTemp[i1];
        if (value == null || value == "" || value == "sign") {
            continue;
        }
        sPara.push(value);
    }
    sPara = sPara.sort();
    return sPara;
}